package com.jqb.webservice.ums.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import com.sun.xml.ws.api.message.Header;
import com.sun.xml.ws.api.message.Headers;
import com.sun.xml.ws.developer.WSBindingProvider;

import ums.webservice.jqb.com.userservice.IUserService;
import ums.webservice.jqb.com.userservice.LicenceInfo;
import ums.webservice.jqb.com.userservice.User;
import ums.webservice.jqb.com.userservice.UserService;

public class UserServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IUserService port;
	private UserService userService;
	private String ns = "http://com.jqb.webservice.ums/UserService";
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		System.out.println("method:"+method);
		userService = new UserService();
		port = userService.getUserServicePort();
		if(method==null||"".equals(method)){
			getUsers(request,response);
		}else if("login".equals(method)){
			login(request,response);
		}else if("addUser".equals(method)){
			addUer(request,response);
		}else if("getUser".equals(method)){
			getUser(request,response);
		}else if("updateUser".equals(method)){
			update(request,response);
		}else if("deleteUser".equals(method)){
			delete(request,response);
		}else if("addUi".equals(method)){
			addUi(request,response);
		}else if("updateUi".equals(method)){
			updateUi(request,response);
		}
	}
	private void updateUi(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		User user = port.getUser(id);
		request.setAttribute("user", user);
		request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
		
	}
	private void addUi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/jsp/add.jsp").forward(request, response);
		
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		port.deleteUser(id);
		response.sendRedirect(this.getServletContext().getContextPath()+"/UserServlet");
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = new User();
		user.setId(Integer.parseInt(request.getParameter("id")));
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		port.updateUser(user);
		response.sendRedirect(this.getServletContext().getContextPath()+"/UserServlet");
	}

	private void getUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		User user = port.getUser(id);
		request.setAttribute("user", user);
		request.getRequestDispatcher("/WEB-INF/jsp/user.jsp").forward(request, response);
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		try {
			port.login(username, password);
			request.getSession().setAttribute("user", username);
			response.sendRedirect(this.getServletContext().getContextPath()+"/UserServlet");
		} catch (Exception e) {
			System.out.println(e.getMessage());
			request.setAttribute("err", e.getMessage());
			request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		}
	}

	private void getUsers(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<User> users = port.getUsers();
		System.out.println("userList.size="+users.size());
		request.setAttribute("users", users);
		request.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(request, response);
	}

	private void addUer(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		User user = new User();
		user.setId(Integer.parseInt(request.getParameter("id")));
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		addHeader();
		try {
			port.addUser(user);
			response.sendRedirect(this.getServletContext().getContextPath() + "/UserServlet");
		} catch (Exception e) {
			System.out.println(e.getMessage());
			request.setAttribute("err", e.getMessage());
			request.getRequestDispatcher("/WEB-INF/jsp/add.jsp").forward(request, response);
		}
	}
	
	public void addHeader(){
		User user = new User();
		user.setId(1000);
		user.setUsername("admin");
		user.setPassword("admin123");
		LicenceInfo licence = new LicenceInfo();
		licence.setRegisteredUser(user);
		try {
			// 使用JAXB编排对象到xml
			JAXBContext jaxbCtx = JAXBContext.newInstance(LicenceInfo.class);
			QName qname = new QName(ns, "licenceInfo");
			JAXBElement<LicenceInfo> jaxbElement = new JAXBElement<LicenceInfo>(qname, LicenceInfo.class, licence);
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Marshaller marshaller = jaxbCtx.createMarshaller();
			marshaller.marshal(jaxbElement, doc);
			// 创建头信息
			Header header = Headers.create(doc.getDocumentElement());
			// 绑定头信息(port其实是一个实现了WSBindingProvider和IUserService接口的代理类)
			WSBindingProvider provider = (WSBindingProvider) port;
			provider.setOutboundHeaders(header);
			// 经过以上的倒腾就编排出了一条soap头消息
			/*
			 * <S:Header>
			 * 	<licenceInfo xmlns="http://com.jqb.webservice.ums/UserService">
			 * 		<registeredUser>
			 * 			<id>1000</id><username>admin</username><password>admin123</password>
			 *		</registeredUser>
			 * 	</licenceInfo>
			 * </S:Header>
			 */
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
}
